/*****************************************************************************
 *   Copyright 2005 Tim A Wang
 *
 *   Licensed under the Apache License, Version 2.0 (the "License");
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 *
 ****************************************************************************/
package com.jb.web.renderer;

import com.jb.web.bean.TextField;
import com.jb.web.context.WebContext;

import com.jb.faces.component.UIComponent;

public class TextFieldRenderer extends FormItemRenderer {
    public StringBuffer render(WebContext pCtx, UIComponent itemToRender) {
        TextField formField = (TextField) itemToRender;
        Object value = formField.getModelBean();

        if (value == null) {
            String strValue = formField.getValue();

            if (isEmptyString(strValue)) {
                value = evaluate(pCtx, formField, formField.getDefaultValue());
            } else {
                value = evaluate(pCtx, formField, strValue);
            }
        }

        if (formField.isHidden()) {
            return hiddenField(pCtx, formField, "" + value);
        }

        StringBuffer html = new StringBuffer("<span><INPUT name=\"").append(formField.getFieldName(pCtx)).append("\"")
                                                                    .append(addTagProperty("type", "text", "text"));

        if (pCtx.isRunTime()) {
            html.append(addTagProperty("disabled", formField.isEnabled() ? "" : "disabled", null));
        }

        html.append(addTagProperty("size", formField.getWidth(), null)).append(addTagProperty("value", "" + value, null));

        if (formField.getMaxLength() > 0) {
            html.append(addTagProperty("maxlength", "" + formField.getMaxLength(), "32"));
        }

        html.append(addTagProperty("accessKey", formField.getAccessKey(), null))
        .append(addTagProperty("onkeypress", formField.getOnAutoSubmit(), null))
        .append(addTagProperty("style", formField.getStyle(pCtx), null))
            .append(addTagProperty("class", formField.getStyleClass(), null))
            .append(getEditScript(pCtx, formField))
            .append(" />");

        if (pCtx.isError()) {
            html.append(renderError(pCtx, formField));
        }

        return html;
    }
}
